import React, { PureComponent } from 'react';
import {connect} from 'dva'
import {Icon, Upload, Button} from 'antd'
import path from 'path';
import styles from './index.less'


import { QINIU_DOMAIN, QINIU_UPLOAD_DOMAIN, TASK_APPROVE_STATUS, SOURCE, CHANNELS_FOR_CASCADER, TASK_TYPES } from '../../../constants';

@connect(state => ({
  qiniucloud: state.qiniucloud,
}))

export default class FileUpload extends PureComponent {
  state = {
  }
  makeUploadData = (file) => {
    const { qiniucloud } = this.props;
    const extname = path.extname(file.name);
    console.log('file.name: ', file.name)
    return {
      token: qiniucloud.uptoken,
      key: `${file.uid}${extname}`,
    };
  }
  beforeUpload = (file) => {
    const promise = new Promise(function(resolve, reject) {
      const isLt100M = file.size / 1024 / 1024 <= 100;
      if (!isLt100M) {
        message.error('上传文件最大100M');
        reject(isLt100M);
      }
      resolve(isLt100M);
    });
    return promise;
  }
  onUploadChanhe = (data) => {
    if(data.file.response) {
      let {file, fileList} = data
      if(file.response) {
        let temp = []
        fileList.forEach(item => {
          temp.push(`${QINIU_DOMAIN}/${item.response.key}`)
        })
        this.props.onChange(temp);
      }
    }
  }
  render() {
    let defaultFileList = []
    this.props.value.map((item,idx) => {
      defaultFileList.push({
        uid: idx,
        name: item.replace(`${QINIU_DOMAIN}/`, ''),
        status: 'done',
        url: item,
      })
    })
    return (
      <div>
       <Upload name="file"
          listType='text'
          action={QINIU_UPLOAD_DOMAIN}
          data={this.makeUploadData}
          beforeUpload={this.beforeUpload}
          onChange={this.onUploadChanhe}
          defaultFileList={defaultFileList}
        >
          <Button>
            <Icon type="upload" /> 点击上传附
          </Button>
        </Upload>
      </div>
    )
  }
}
